package hnx.ca.util;
import hnx.ca.util.Base64Utils;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.PublicKey;
import java.security.Security;
import java.security.Signature;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;


public class Test {

	public static void main(String args[]) throws Exception{
		try {
			method1();
		} catch (CertificateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static void method1() throws Exception{
		File f= new File("D:\\RED ARROW\\cerfile.cer");    
		CertificateFactory cf = CertificateFactory.getInstance("X.509");
		BufferedInputStream in = new BufferedInputStream(new FileInputStream(f));
		Certificate cert = null;
		while (in.available() > 0) {
			cert = cf.generateCertificate(in); 
		}
		PublicKey publicKey = cert.getPublicKey();
		System.out.println(publicKey);
		String orignialText = "test noi dung ma hoa";
		String signContext = "bWFxYlaOM1k6SjYZiwdXqu6k7o6yAd5d2f7mCYxMS91JjasUkGEoDh30rK4jbEy0MFaEF+ZrHP0YioUvtWcS+fQF0ser00YEwcyciWTivg/5xfQvR79zP92GorY44+Od0pmt35HezYpJ9ne3pSAP4fEWsdrAWdvzEKf60w0WCJ0=";
		byte[] sign = Base64Utils.base64Decode(signContext);
		verifySig(orignialText.getBytes(), publicKey, sign);
	}
	
	public static boolean verifySig(byte[] data, PublicKey key, byte[] sig) throws Exception {
		Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
		Signature signer = Signature.getInstance("SHA1withRSA","BC");
	    signer.initVerify(key);
	    signer.update(data);

	    boolean valido = false;
	    try{
	        valido = signer.verify(sig);
	    }catch(Exception e){
	        e.printStackTrace();
	        valido = false;
	    }
	    System.out.println(valido);
	    return valido;

	  }
}
